from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
import random
from rest_framework import status
from django_redis import get_redis_connection
from celery_tasks.sms.tasks import send_sms_code
from . import constants
import logging
logger = logging.getLogger('django')


class SMSCodeView(APIView):
    '''短信验证'''

    def get(self, request, mobile):
        '''
        1.生成验证码
        2.创建redis链接对象
        3.把验证码存到redis数据库
        4.利用容联云通信发送短信验证码
        5.响应
        '''
        #先从redis中取出发送标记
        # 获取一个redis的链接对象
        redis_conn = get_redis_connection('verify_codes')
        send_flag = redis_conn.get('send_flag_%s'%mobile)
        if send_flag: #如果请求有值,说明用户已经发送过验证码
            return Response({'message':'手机已经发送过验证码'},status = status.HTTP_400_BAD_REQUEST)
        sms_code = random.randint(0, 999999)
        logger.info(sms_code)
        #创建redis管道(把多次的redis操作装进管道,以后一次性操作,减少redis的连接操作)
        pl=redis_conn.pipeline()
        # 存到redis
        #redis_conn.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        #存储一个标记,表示此手机号码已经发送过短信,短信的有效期60s
        #redis_conn.setex('sms_flag_%s'%mobile,constants.SEND_SMS_CODE_INTERVAL,1)
        pl.setex('send_flag_%s'%mobile,constants.SEND_SMS_CODE_INTERVAL,1)
        pl.execute()
        # 发送短息
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        send_sms_code.delay(mobile,sms_code)#触发异步任务
        return Response('OK')
